﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wsitech.BLL;
using Wsitech.Model;

public partial class Backend_Admin_UserAdd : BackendPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindRole();
            if (Request["uid"] != null)
            {
                initUser(Request["uid"]);
            }
        }
    }

    //绑定角色数据
    private void bindRole()
    {
        ddlRole.DataSource = AdminRoleBLL.Instance.GetActiveList();
        ddlRole.DataTextField = "RoleName";
        ddlRole.DataValueField = "RoleId";
        ddlRole.DataBind();

        ddlRole.Items.Insert(0, new ListItem("==请选择==", ""));
    }
    private void initUser(string userid)
    {
        AdminUser user = AdminUserBLL.Instance.GetDetail(userid);
        if (user != null)
        {
            ddlRole.SelectedValue = string.Join(",", AdminRoleBLL.Instance.GetRoleListByUserId(user.UserID).Select(r => r.RoleID));
            txtUserName.Text = user.UserName;

            //隐藏密码输入，显示密码重设
            panelPassword.Visible = false;
            panelNewPsw.Visible = true;
        }
    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (CheckParams())
        {
            //添加
            if (Request["uid"] == null)
            {
                AdminUserBLL.Instance.AddUser(ddlRole.SelectedValue, txtUserName.Text.Trim(), txtPassword.Text.Trim());

            }
            //编辑
            else
            {
                AdminUserBLL.Instance.UpdateUser(Request["uid"], ddlRole.SelectedValue, txtUserName.Text.Trim(), txtNewPassword.Text.Trim());
            }
            base.RefreshParent();
        }
    }

    //数据验证
    private bool CheckParams()
    {
        //角色
        if (ddlRole.SelectedIndex == 0)
        {
            base.Alert("请选择用户所属的角色！");
            return false;
        }
        //用户名
        if (txtUserName.Text.Trim() == "")
        {
            base.Alert("用户名不能为空！");
            return false;
        }
        else
        {
            //判断用户是否已经存在
            AdminUser user = AdminUserBLL.Instance.GetDetailByUserName(txtUserName.Text.Trim());
            if (user != null && user.UserID != Request["uid"])
            {
                base.Alert("该用户已存在！");
                return false;
            }
        }
        //用户密码
        if (Request["uid"] == null && txtPassword.Text.Trim() == "")
        {
            base.Alert("用户密码不能为空！");
            return false;
        }
        return true;
    }
}